package com.igeek.health.exception;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description 全局异常处理器（一个系统对应只有一个全局异常处理器）
 * @Author chenmin
 * @Version 1.0
 * @Date 2023/2/13 10:45
 */
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {

    /**
     * 处理异常
     * @param request  请求
     * @param response 响应
     * @param handler  正在执行的handler
     * @param ex       触发的异常对象
     * @return         ModelAndView对象
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //全类名#方法(形参列表)
        //com.igeek.ssm.controller.ItemsController#viewOne(int, Model)
        //System.out.println("handler = "+handler);

        CustomException customException = null;

        if(ex instanceof CustomException){
            customException = (CustomException)ex;
        }else{
            customException = new CustomException("未知错误");
        }

        //统一返回视图
        ModelAndView mv = new ModelAndView();
        //设置请求域参数
        mv.addObject("errorMsg",customException.getMessage());
        //设置逻辑视图名  /templates/error.html
        mv.setViewName("error");
        return mv;
    }
}
